package com.js.data.dtmg.quartz;

import com.js.data.common.utils.StringUtils;
import com.js.data.dtmg.entity.DtTaskLog;
import com.js.data.dtmg.entity.DtTask;
import com.js.data.dtmg.service.DtTaskLogService;
import com.js.data.dtmg.service.DtTaskService;
import com.js.data.dtmg.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 *
 * @author Administrator
 */
@Slf4j
@DisallowConcurrentExecution
public class TaskJobDetail extends QuartzJobBean {

    @Resource
    DtTaskLogService crontabLogService;
    @Resource
    DtTaskService taskService;

    @Override
    public void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("begin delwith quartz task >>>>>>>>>>>>>>>>>>>>>>>");
        String batchId = context.getJobDetail().getKey().getName();
        JobDataMap mergedJobDataMap = context.getMergedJobDataMap();
        executeTask(mergedJobDataMap);
        log.info("执行的任务id为：[{}]", batchId);
        log.info("JobDataMap：[{}]", mergedJobDataMap);
    }

    /**
     * 定时任务处理方法
     *
     * @param mergedJobDataMap 参数
     */
    @Transactional(rollbackFor = Exception.class)
    private void executeTask(JobDataMap mergedJobDataMap) {
        DtTask task = (DtTask) mergedJobDataMap.get("task");
        log.info("参数：{}", task.getInParam());
        //记录任务日志
        DtTaskLog dtTaskLog = new DtTaskLog();
        dtTaskLog.setTaskId(task.getId());
        dtTaskLog.setTaskName(task.getTaskName());
        dtTaskLog.setInParam(DbUtil.replaceParam(task.getInParam()));
        //0处理中
        dtTaskLog.setResult(0);
        dtTaskLog.setBegTime(LocalDateTime.now());
        crontabLogService.save(dtTaskLog);
        //处理任务信息
        Map<String,Object> mapRtn = taskService.doTask(task,"");
        String errMsg = (String)mapRtn.get("errMsg");
        if (StringUtils.isEmpty(errMsg)) {
            //1处理成功 2处理失败
            dtTaskLog.setResult(1);
            dtTaskLog.setInNum(Long.parseLong(String.valueOf(mapRtn.get("inNum"))));
            dtTaskLog.setDoNum(Long.parseLong(String.valueOf(mapRtn.get("doNum"))));
       } else {
            dtTaskLog.setResult(2);
            dtTaskLog.setResultRemarks(errMsg.substring(0,500));
       }
        dtTaskLog.setInTimeNo((String)mapRtn.get("inTimeNo"));
        dtTaskLog.setEndTime(LocalDateTime.now());
        crontabLogService.updateById(dtTaskLog);
    }

}
